package com.kingray.openfire.plugin.handler.iq;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.IQRouter;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.disco.ServerFeaturesProvider;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.session.ClientSession;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;

import com.kingray.openfire.plugin.dao.MessageDAO;
import com.kingray.openfire.plugin.dao.impl.MessageDAOImpl;
import com.kingray.openfire.plugin.packet.IQElementMapping;
import com.kingray.openfire.plugin.packet.KingrayNameSpace;
import com.kingray.openfire.plugin.packet.MessageHistoryIQ;
import com.kingray.openfire.plugin.vo.MessageVO;
import com.xiongyingqi.convert.XmlConvert;
import com.xiongyingqi.util.CalendarHelper;
import com.xiongyingqi.util.DateHelper;
import com.xiongyingqi.util.StringHelper;

/**
 * 服务类，用于处理客户端的数据查询等请求
 * @author XiongYingqi
 * 
 */
public class KingrayMessageHistoryIQHandler extends IQHandler implements ServerFeaturesProvider {
	private static final KingrayNameSpace QUERY_MESSAGE = KingrayNameSpace.QUERY_MESSAGE; // 命名空间
	private MessageDAO messageDAO;
	private XmlConvert convert;
	
	private IQHandlerInfo info;
	
	private String serverString;
	
	public KingrayMessageHistoryIQHandler() {
		super(QUERY_MESSAGE.getKey()); // 取一个处理器名
		messageDAO = new MessageDAOImpl();
		convert = new XmlConvert(IQElementMapping.class);
		info = new IQHandlerInfo(QUERY_MESSAGE.getKey(), QUERY_MESSAGE.getValue());
		
		XMPPServer server = XMPPServer.getInstance();
		serverString = server.getServerInfo().getXMPPDomain();
		
		// 注册IQ处理服务
		IQRouter iqRouter = server.getIQRouter();
		iqRouter.addHandler(this);
		
//		server.getServerFeaturesProviders().add(this);
//		server.getIQDiscoInfoHandler().addServerFeature(QUERY_MESSAGE.getValue());
		
	}

	@Override
	public IQ handleIQ(IQ packet) throws UnauthorizedException {
		IQ response = handleMessageHistory(packet);
		
		response.setType(IQ.Type.result);
		response.setFrom(serverString);
		JID fromJid = packet.getFrom();
		ClientSession session = XMPPServer.getInstance().getSessionManager().getSession(fromJid);
		if(session == null){ // 
			response.setChildElement(packet.getChildElement().createCopy());
			response.setError(PacketError.Condition.not_authorized);
		}
//		session.process(response);
//		deliverer.deliver(response);
		
//		response = null;
		return response;
	}
	
	/**
	 * 处理消息记录
	 * <br>2013-6-18 上午9:49:27
	 * @param packet
	 * @return
	 */
	public IQ handleMessageHistory(IQ packet){
		IQ response = IQ.createResultIQ(packet);
		
		String userName = packet.getFrom().getNode();
		
		// 读取根节点数据
		Element element = packet.getChildElement();
		String relationUserName = element.attributeValue("relationUserName");
		String actionType = element.attributeValue("actionType");
		String messageDateTimeStr = element.attributeValue("messageDateTime");
		
		Date messageDateTime = null;
		if(StringHelper.notNullAndNotEmpty(messageDateTimeStr)){
			try {
				messageDateTime = DateHelper.strToDate(messageDateTimeStr);
			} catch (Exception e) {
			}
		}
		
		//读取<message节点数据>
		Collection<Long> messageIds = new HashSet<Long>();
		Collection<String> sendMessageIds = new HashSet<String>();
		
		List messageElements = element.elements();
		for (Iterator iterator = messageElements.iterator(); iterator.hasNext();) {
			Element messageElement = (Element) iterator.next();
			String messageIdStr = messageElement.attributeValue("messageId"); // 优先读取messageId
			if(StringHelper.notNullAndNotEmpty(messageIdStr)){
				Long messageId = Long.parseLong(messageIdStr);
				messageIds.add(messageId);
			} else { // 如果不存在messageId属性，则读取sendMessageId
				String sendMessageId = messageElement.attributeValue("sendMessageId");
				if(StringHelper.notNullAndNotEmpty(sendMessageId)){
					sendMessageIds.add(sendMessageId);
				}
			}
		}
		
		if(!StringHelper.notNullAndNotEmpty(actionType)){ // 判断是否指定actionType，如果没有指定，则默认使用QUERY_COUNT
			actionType = MessageHistoryIQ.MessageHistoryActionType.QUERY_COUNT.toString();
		} 
		Element resultElement = null;
		
		if(actionType.equals(MessageHistoryIQ.MessageHistoryActionType.QUERY_COUNT.toString())){ // 查询条数
			int messageHistoryCount = messageDAO.getMessageHistoryCountByUserName(userName, relationUserName, messageDateTime);
			resultElement = handleMessageHistoryCountResponseIQ(response, messageHistoryCount, relationUserName, messageDateTime);
		} else if(actionType.equals(MessageHistoryIQ.MessageHistoryActionType.QUERY_SUMMARY.toString())){ // 查询预览
			Collection<MessageVO> messageVOs = messageDAO.getMessageHistorySummaryByUserName(userName, relationUserName, messageDateTime);
			resultElement = convert.convertVOs(messageVOs); // 将获取的数据转换为xml
		} else if(actionType.equals(MessageHistoryIQ.MessageHistoryActionType.QUERY_DETAIL.toString())){ // 查询详细消息
			Collection<MessageVO> messageVOs = null;
			// 检查查询条件，如果查询条件不足，那么就返回错误
			if(messageIds != null && messageIds.size() > 0){
				messageVOs = messageDAO.getMessageHistoryDetailByMessageIds(messageIds);
			} else if(sendMessageIds != null && sendMessageIds.size() > 0){
				messageVOs = messageDAO.getMessageHistoryDetailBySendMessageIds(sendMessageIds);
			} else if(StringHelper.notNullAndNotEmpty(userName)){
				messageVOs = messageDAO.getMessageHistoryDetailByUserName(userName, relationUserName, messageDateTime);
			} else { // 查询条件不足，返回错误
				response.setChildElement(packet.getChildElement().createCopy());
				response.setError(PacketError.Condition.bad_request);
				return response;
			}
			
			if(messageVOs != null){
				resultElement = convert.convertVOs(messageVOs); // 将获取的数据转换为xml
			}
		}
		System.out.println("resultElement ======== " + resultElement);
		resultElement.addAttribute("actionType", actionType); // 加入actionType
		resultElement.addNamespace("", QUERY_MESSAGE.getValue()); // 加入命名空间
		response.setChildElement(resultElement);
		
		return response;
	}
	/**
	 * 返回总消息数的IQ
	 * <br>2013-6-17 下午3:26:22
	 * @param packet
	 * @param messageCount
	 * @param relationUserName
	 * @param messageDateTime
	 * @return
	 */
	public Element handleMessageHistoryCountResponseIQ(IQ packet, int messageHistoryCount, String relationUserName, Date messageDateTime){
		Element element = DocumentHelper.createElement(QUERY_MESSAGE.getKey());
//		Element messageHistoryCountElement = DocumentHelper.createElement("messageHistoryCount");
//		messageHistoryCountElement.setData(messageHistoryCount);
//		element.add(messageHistoryCountElement);
		element.addAttribute("messageHistoryCount", messageHistoryCount + "");
		if(StringHelper.notNullAndNotEmpty(relationUserName)){
			element.addAttribute("relationUserName", relationUserName);
		}
		if(messageDateTime != null){
			element.addAttribute("messageDateTime", DateHelper.dateToStr(messageDateTime));
		}
		element.addNamespace("", QUERY_MESSAGE.getValue()); // 加入命名空间
//		packet.setChildElement(element);
		return element;
	}
	
	/**
	 * 必须实现该方法，否则openfire将无法实例化本处理器
	 */
	@Override
	public IQHandlerInfo getInfo() {
		return info;
	}
	public static void main(String[] args) {
		JID jid = new JID("熊瑛琪", "szkingray.3322.org", "金瑞通");
		System.out.println(jid.getNode());
		System.out.println(jid.toBareJID());
		System.out.println(jid.toString());
		
		Date dateOne = DateHelper.strToDate("2013-06-17");
		Date dateTwo = new Date(dateOne.getTime()  + 24 * CalendarHelper.HOUR - 1);
		System.out.println(dateOne);
		System.out.println(dateTwo);
	}

	/**
	 * <br>2013-6-19 下午5:56:05
	 * @see org.jivesoftware.openfire.disco.ServerFeaturesProvider#getFeatures()
	 */
	@Override
	public Iterator<String> getFeatures() {
		ArrayList<String> features = new ArrayList<String>();
        features.add(QUERY_MESSAGE.getValue());
        return features.iterator();
	}

}
